package hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution15 {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        back(nums, 0, 0);
        return res;
    }

    public void back(int[] nums, int index, int sum) {
        if (tmp.size() == 3) {
            if (sum == 0) {
                res.add(new ArrayList<>(tmp));
            }
            return;
        }
        for (int i = index; i < nums.length; i++) {
            if (i > index && nums[i] == nums[i - 1]) continue;
            sum += nums[i];
            tmp.add(nums[i]);
            back(nums, i + 1, sum);
            sum -= nums[i];
            tmp.remove(tmp.size() - 1);
        }
    }
}
